<template>
    <van-button
    :icon="isCollected ? 'star':'star-o'"
    :class="{collected: isCollected}"
    :loading="isLoading"
    @click="onCollect"/>
</template>

<script>
import { addCollect, deleteCollect } from '@/api/article'

export default {
    name: 'CollectArticle',
    props: ['isCollected', 'articleId'],
    model: {
        prop: 'isCollected',
        event: 'updateCollected'
    },
    data () {
        return {
            isLoading: false
        }
    },
    methods: {
        async onCollect () {
            this.isLoading = true
            try {
                if (this.isCollected) {
                    // 已收藏->取消收藏
                    await deleteCollect(this.articleId)
                } else {
                    // 未收藏->添加收藏
                    await addCollect(this.articleId)
                }
                this.$emit('updateCollected', !this.isCollected)

                // 由于this.isCollected还没来得及更新因此这里取反
                this.$toast.success(!this.isCollected ? '收藏成功' : '取消收藏')
            } catch (err) {
                this.$toast.fail('操作失败，请重试')
            }
            this.isLoading = false
        }
    }

}
</script>

<style scoped lang="less">
.collected {
    .van-icon {
        color: #ffa500;
    }
}
</style>
